//适用本项目的通用方法
import config from "./config";
import { verifyEmpty, fileApi } from "./function";
export default {
  verifyRule: {
    phone:
      /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
    password: /^(?=.*[a-zA-Z])(?=.*\d)[^]{8,16}$/,
    name: /^[\u4e00-\u9fa5]{2,4}$/,
  },
  /**
   * @description: 过滤数据(脱壳)
   * @param {Object} data 把请求成功的res数据传入进来,或者直接await 请求接口()
   * @param {Function|Boolean} filterFn 可以再传入一个回调函数对返回的数据进行二次处理
   * @param {String} key 可以控制返回的字段
   * @return {Array|Object} 返回值
   */
  filterData(data, filterFn, key) {
    //filterFn为布尔值true时,仅返回data,不获取list
    data = data?.data;
    let list = data?.[key || "list"] || [];
    if (!Array.isArray(list) || typeof filterFn != "function")
      return filterFn ? data || {} : list || [];
    return list.map((res) => filterFn(res));
  },
  filterCover(data, isUrl = true) {
    if (verifyEmpty(data)) return "";
    else if (typeof data === "string") {
      if (uni.$u.test.url(data)) return data;
      else return config.baseURL + data;
    }
    return config.baseURL + (isUrl ? data[0]?.url : data[0]);
  },
  getAvatar(url) {
    //获取头像
    return url ? config.baseURL + url : "/static/image/default-avatar.png";
  },
  getImage(tenement = "", fileName = "", port) {
    if (tenement && !fileName) {
      fileName = tenement;
      tenement = "";
    } else if (tenement) {
      tenement += "/";
    }
    const url = port
      ? config.fileURL.replace(/:\d+$/, ":" + port)
      : config.fileURL;
    if (fileName.lastIndexOf(".") === -1) fileName += ".png"; //默认png后缀
    return url + "/api/file/Image/systemicon/" + tenement + fileName;
  },
  rollback(timeout = 0, { home = {}, ...back } = {}) {
    const pages = getCurrentPages();
    let method = "navigateBack";
    if (pages.length <= 1) {
      back = { url: "/pages/index/index", ...home };
      method = "reLaunch";
    }
    return new Promise((resolve) => {
      setTimeout(() => resolve(uni[method](back)), timeout);
    });
  },
  uploadFile: (url, filePath) => fileApi.upload({ url, filePath }),
  //获取当前位置
  getLocation() {
    let location = {
      lat: 0,
      lng: 0,
    };
    return new Promise((reserve, reject) => {
      //因为获取位置是异步接口所以需要使用promise
      uni.getLocation({
        success(res) {
          location.lat = res.latitude;
          (location.lng = res.longitude), reserve(location);
        },
        fail(err) {
          reject(location); //获取失败则返回经纬坐标为0
        },
      });
    });
  },
  // 数据处理函数
  handleFilterData(arr, key = "_id") {
    return arr.reduce((obj, item) => {
      if (!obj[item[key]]) {
        obj[item[key]] = [];
      }
      obj[item[key]].push(item);
      return obj;
    }, {});
  },
  // 获取经纬度
  getCurrentLocation(address) {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `https://apis.map.qq.com/ws/geocoder/v1/`,
        data: {
          address,
          key: "2DPBZ-DPTKW-VSXR5-YLS7O-DY2A5-ROF6P",
        },
        success: (res) => {
          console.log("解析地址", res.data);
          resolve(res.data.result);
        },
        fail: (error) => {
          console.error("解析地址失败", error);
          reject(error);
        },
      });
    });
  },
  // 防止处理多次点击
  noMultipleClicks(methods, info) {
    // methods是需要点击后需要执行的函数， info是点击需要传的参数
    let that = this;
    if (that.noClick) {
      // 第一次点击
      that.noClick = false;
      if (info && info !== "") {
        // info是执行函数需要传的参数
        methods(info);
      } else {
        methods();
      }
      setTimeout(() => {
        that.noClick = true;
      }, 2000);
    } else {
      // 这里是重复点击的判断
    }
  },
  //根据金纬度计算距离
  distance(lat1, lng1, location) {
    let lat2 = location.lat;
    let lng2 = location.lng;
    let rad1 = (lat1 * Math.PI) / 180.0;
    let rad2 = (lat2 * Math.PI) / 180.0;
    let a = rad1 - rad2;
    let b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
    let s =
      2 *
      Math.asin(
        Math.sqrt(
          Math.pow(Math.sin(a / 2), 2) +
            Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)
        )
      );
    s = s * 6378.137;
    s = Math.round(s * 10000) / 10000;
    s = s.toString();
    s = s.substring(0, s.indexOf(".") + 2);
    return s;
  },
  // 获取当前月时间范围
  getCurrentMonthRange(value = null, separate = "-") {
    // 如果为无效时间,则格式化当前时间
    if (!value) value = +new Date();
    // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
    if (String(value).length == 10 && value == Number(value)) value *= 1000;
    value = Number(value);

    const targetTime = new Date(value);
    const year = targetTime.getFullYear();
    let month = targetTime.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }

    const yDate = new Date(year, Number(month), 0);

    const startDateTime = year + separate + month + separate + "01 00:00:00"; //这个月第一天
    // const endDateTime = year + separate + month + separate + yDate.getDate() + ' 00:00:00'; //这个月最后一天
    const endDateTime =
      year + separate + month + separate + yDate.getDate() + " 23:59:59"; //这个月最后一天

    return [startDateTime, endDateTime];
  },
};
